package com.jcfk.eam.service.base;

import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.eam.dao.base.EamCustomDao;
import com.jcfk.eam.domain.dto.base.EamAssetTypeDTO;
import com.jcfk.eam.domain.dto.base.EamCustomDTO;
import com.jcfk.eam.domain.dto.base.EamCustomValueDTO;
import com.jcfk.eam.domain.dto.base.EamSopItemImgDTO;
import com.jcfk.eam.domain.po.base.EamCustom;
import com.jcfk.eam.domain.po.base.EamCustomData;
import com.jcfk.eam.domain.po.base.EamCustomValue;
import com.jcfk.eam.domain.query.base.EamCustomQuery;
import com.jcfk.eam.domain.query.base.EamCustomValueQuery;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

import java.util.*;

import java.util.stream.Collectors;

/**
 * 自定义字段
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-08-15
 */
@Service
public class EamCustomService extends BaseService<EamCustomDao, EamCustom> {


    @Autowired
    private EamCustomValueService eamCustomValueService;


    @Autowired
    private EamCustomDataService eamCustomDataService;

    @Autowired
    private EamAssetTypeService eamAssetTypeService;

    /**
     * EamCustom分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamCustomDTO> queryByPage(DataPage<EamCustomDTO> page, EamCustomQuery query) {
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamCustomDTO>
     */
    public List<EamCustomDTO> getList(EamCustomQuery query) {
        // 查询条件
        QueryWrapper<EamCustom> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getType()), EamCustom::getType, query.getType());
        qw.lambda().eq(query.getAssetKind() != null, EamCustom::getAssetKind, query.getAssetKind());
        qw.lambda().eq(query.getEnabled() != null, EamCustom::getEnabled, query.getEnabled());
        qw.lambda().eq(!StrUtil.isEmpty(query.getEquipTypeId()), EamCustom::getEquipTypeId, query.getEquipTypeId());
        qw.lambda().eq(EamCustom::getDeleted, 0);

        qw.lambda().eq(query.getEnabled() != null, EamCustom::getEnabled, query.getEnabled());
        qw.lambda().orderByAsc(EamCustom::getSort);

        // 查询数据
        List<EamCustom> list = super.list(qw);

        return convertList(list, EamCustomDTO.class);
    }

    /**
     * 获取根据关联id详情表列表
     *
     * @param query 查询条件
     * @return List<EamCustomDTO>
     */
    public List<EamCustomValueDTO> getDetails(EamCustomQuery query) {
        // 查询条件
        QueryWrapper<EamCustomValue> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getId()), EamCustomValue::getCustomId, query.getId());

        // 查询数据
        List<EamCustomValue> list = eamCustomValueService.list(qw);

        return convertList(list, EamCustomValueDTO.class);
    }


    /**
     * 判断EamCustom是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamCustomDTO dto) {
        QueryWrapper<EamCustom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        queryWrapper.lambda().eq(EamCustom::getName, dto.getName());
        queryWrapper.lambda().eq(EamCustom::getAssetKind, dto.getAssetKind());
        queryWrapper.lambda().eq(EamCustom::getEquipTypeId, dto.getEquipTypeId());

        if (!StringUtils.isEmpty(dto.getId())) queryWrapper.ne("id", dto.getId());
        Integer count = this.count(queryWrapper);

        if (count > 0) return RetResult.fail("方案代码已存在");

        return RetResult.ok();
    }

    /**
     * 插入自定义字段
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamCustomDTO dto) {

        // 保存
        EamCustom item = new EamCustom();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);

        // 设置关联主键
        for (EamCustomValueDTO detail : dto.getDetails()) {
            detail.setCustomId(item.getId());
        }

        // 保存明细表
        eamCustomValueService.saveBatch(dto.getDetails(), item.getId());
    }


    /**
     * 更新自定义字段
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamCustomDTO dto) {

        // 保存
        EamCustom item = new EamCustom();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        // 设置关联主键
        for (EamCustomValueDTO detail : dto.getDetails()) {
            detail.setCustomId(item.getId());
        }
        // 保存明细表
        eamCustomValueService.saveBatch(dto.getDetails(), item.getId());
    }


    /**
     * 根据批量主键删除自定义字段(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamCustomDTO dto) {

        EamCustom item = new EamCustom();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamCustom> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamCustom item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());
    }


    /**
     * 根据主键获取自定义字段信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamCustomDTO get(String id) {
        // 查询数据
        EamCustom item = this.baseMapper.selectById(id);
        EamCustomDTO dto = new EamCustomDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        EamAssetTypeDTO eamAssetTypeDTO = eamAssetTypeService.get(dto.getEquipTypeId());
        dto.setAssetTypeCode(eamAssetTypeDTO.getAssetTypeCode());
        dto.setAssetTypeName(eamAssetTypeDTO.getAssetTypeName());

        return dto;
    }


    /**
     * 根据主键获取自定义字段信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        EamCustom item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }


    /**
     * 根据主键获取自定义字段信息
     *
     * @param query 主键
     * @return StandardCodeDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public List<EamCustomDTO> getConfiguration(EamCustomQuery query) {
        // 查询数据
        query.setEnabled(1);
        List<EamCustomDTO> dtos = this.getList(query);

        List<String> ids = dtos.stream().map(EamCustomDTO::getId).collect(Collectors.toList());
        if (ids.size() > 0) {
            QueryWrapper<EamCustomValue> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(EamCustomValue::getCustomId, ids);
            List<EamCustomValue> eamCustomValueList = eamCustomValueService.list(queryWrapper);
            List<EamCustomValueDTO> eamCustomValueDTOS = convertList(eamCustomValueList, EamCustomValueDTO.class);

            Map<String, List<EamCustomValueDTO>> values = new HashMap<>();

            // 将节点按照父节点进行分组
            for (EamCustomValueDTO node : eamCustomValueDTOS) {
                String id = node.getCustomId();
                values.computeIfAbsent(id, k -> new ArrayList<>()).add(node);
            }

            for (EamCustomDTO eamCustomDTO : dtos) {
                eamCustomDTO.setSelectValues(values.get(eamCustomDTO.getId()));
            }

            // 选中值
            if (!StringUtils.isEmpty(query.getRelationId())) {
                QueryWrapper<EamCustomData> eamCustomDataQueryWrapper = new QueryWrapper<>();
                eamCustomDataQueryWrapper.lambda().eq(EamCustomData::getRelationId, query.getRelationId());
                eamCustomDataQueryWrapper.lambda().eq(EamCustomData::getAssetKind, query.getAssetKind());
                List<EamCustomData> datas = eamCustomDataService.list(eamCustomDataQueryWrapper);

                Map<String, List<String>> selectdDataMaps = new HashMap<>();
                Map<String, String> dataMaps = new HashMap<>();

                // 将节点按照父节点进行分组
                for (EamCustomData node : datas) {
                    String id = node.getCustomId();
                    selectdDataMaps.computeIfAbsent(id, k -> new ArrayList<>()).add(node.getCustomData());
                    dataMaps.put(id, node.getCustomData());
                }

                for (EamCustomDTO eamCustomDTO : dtos) {
                    if (eamCustomDTO.getType().equals("1") || eamCustomDTO.getType().equals("2") || eamCustomDTO.getType().equals("6") || eamCustomDTO.getType().equals("7")) {
                        eamCustomDTO.setDataValue(dataMaps.get(eamCustomDTO.getId()));
                    } else {
                        eamCustomDTO.setSelectedValues(selectdDataMaps.get(eamCustomDTO.getId()));
                    }
                }

            }

        }

        return dtos;
    }

    /**
     * 插入自定义字段
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveEamCustoms(List<EamCustomDTO> dto, String id, Integer assetKind) {

        List<EamCustomData> dataList = new ArrayList<>();
        QueryWrapper<EamCustomData> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamCustomData::getRelationId, id);
        queryWrapper.lambda().eq(EamCustomData::getAssetKind, assetKind);
        // 删除历史数据
        eamCustomDataService.remove(queryWrapper);

        for (EamCustomDTO eamCustomDTO : dto) {

            if (eamCustomDTO.getType().equals("1") || eamCustomDTO.getType().equals("2") || eamCustomDTO.getType().equals("6") || eamCustomDTO.getType().equals("7")) {
                EamCustomData data = new EamCustomData();
                data.setCustomId(eamCustomDTO.getId());
                data.setAssetKind(eamCustomDTO.getAssetKind());
                data.setCustomData(eamCustomDTO.getDataValue());
                data.setRelationId(id);
                data.setAssetKind(assetKind);

                eamCustomDataService.setDefaultValue(data);
                dataList.add(data);
            } else {
                for (String selectedValue : eamCustomDTO.getSelectedValues()) {
                    EamCustomData data = new EamCustomData();
                    data.setCustomId(eamCustomDTO.getId());
                    data.setAssetKind(eamCustomDTO.getAssetKind());
                    data.setCustomData(selectedValue);
                    data.setRelationId(id);
                    data.setAssetKind(assetKind);

                    eamCustomDataService.setDefaultValue(data);
                    dataList.add(data);
                }
            }

        }

        if (dataList.size() > 0)
            eamCustomDataService.saveBatch(dataList);
    }

}

